package org.fu.crowd.service.impl;

import org.fu.crowd.entity.Admin;
import org.fu.crowd.entity.Role;
import org.fu.crowd.mvc.config.SecurityAdmin;
import org.fu.crowd.service.api.AdminService;
import org.fu.crowd.service.api.AuthService;
import org.fu.crowd.service.api.RoleService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Component
public class CrowdUserDetailsService implements UserDetailsService {

    @Resource
    private AdminService adminService;

    @Resource
    private RoleService roleService;

    @Resource
    private AuthService authService;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据账号名称查询admin对象
        Admin admin = adminService.getAdminByLoginAcct(username);

        //获取id
        Integer adminId = admin.getId();
        //根据id查询角色信息
        List<Role> assignRole = roleService.getAssignRole(adminId);
        System.out.println(assignRole);
        //根据id查询权限信息
        List<String> name = authService.getAssignedAuthNameByAdminId(adminId);
        //创建集合对象存储角色和权限
        List<GrantedAuthority> authorities = new ArrayList<>();
        //遍历角色信息
        for (Role role : assignRole){
            String roleName = "ROLE_"+role.getName();
            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(roleName);
            authorities.add(simpleGrantedAuthority);
        }
        //遍历权限
        for (String authName : name){
            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(authName);
            authorities.add(simpleGrantedAuthority);
        }
        //封装
        SecurityAdmin securityAdmin = new SecurityAdmin(admin, authorities);

        return securityAdmin;
    }
}
